#include "io_thread_pool.h"
#include "singleton.h"
#include "server.h"

#include <atomic>
#include <iostream>

#include <boost/asio/io_context.hpp>

std::atomic_bool g_stop{false};
std::mutex g_mtx;
std::condition_variable g_cv;

int main(void)
{
    try
    {
        //初始化IOContextPool
        auto pool = Singleton<IOThreadPool>::GetInstance();

        boost::asio::io_context ioc;
        //捕获对应ioc的信号
        boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
        //异步等待信号
        signals.async_wait([&ioc, &pool](boost::system::error_code ec, int signum){
            if(ec)
                return;
            std::cout << "\tSignal: " << signum << "\n";
            ioc.stop();
            pool->Stop();
            g_stop = true;
            g_cv.notify_one();
        });

        Server server(pool->GetIOContext(), 8080);
        {
            std::unique_lock<std::mutex> lk(g_mtx);
            while(!g_stop)
                g_cv.wait(lk);
        }

        ioc.run();
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
        return -1;
    }
    return 0;
}